package user

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"ttsx/server/common/global"
	"ttsx/server/model"
	"ttsx/server/utils"
)

func ToLogin(ctx *gin.Context) {
	ctx.HTML(http.StatusOK, "user/login.html", nil)
}

func DoLogin(ctx *gin.Context) {
	// 获取数据
	username := ctx.PostForm("user_name")
	password := ctx.PostForm("pwd")
	remember := ctx.PostForm("remember")

	// 校验数据
	if username == "" || password == "" {
		ctx.HTML(http.StatusOK, "user/login.html", map[string]string{"errMsg": "请输入用户名或密码"})
		return
	}

	// 验证用户名密码
	var NewLoginUser model.User
	if ret := global.App.DB.Where("name = ?", username).Find(&NewLoginUser); ret.RowsAffected == 0 {
		global.App.Log.Sugar().Errorf("登录的用户不存在：%q", ret.Error)
		ctx.HTML(http.StatusOK, "user/login.html", map[string]string{"errMsg": "登录用户不存在"})
		return
	}

	if ok := utils.CheckPwd(NewLoginUser.Password, password); !ok {
		global.App.Log.Error("登录密码错误")
		ctx.HTML(http.StatusOK, "user/login.html", map[string]string{"errMsg": "登录密码错误"})
		return
	}

	if !NewLoginUser.IsActive {
		global.App.Log.Sugar().Errorf("User: %s ==> ActiveStatus: %q", NewLoginUser.Name, NewLoginUser.IsActive)
		ctx.HTML(http.StatusOK, "user/login.html", map[string]string{"errMsg": "登录用户未激活，请激活后登录"})
		return
	}

	// 记住登录状态- cookies
	if remember == "on" {
		ctx.SetCookie("username", NewLoginUser.Name, 7*24*3600, "/ttsx", global.App.Config.App.APPUrl, false, true)
	} else {
		ctx.SetCookie("username", NewLoginUser.Name, 60, "/ttsx", global.App.Config.App.APPUrl, false, true)
	}
	global.App.Log.Sugar().Infof("用户登录成功：%q", map[string]interface{}{"username": username, "password": password})
	ctx.Redirect(http.StatusFound, "/ttsx/index")
}

func Logout(ctx *gin.Context) {
	cookie, _ := ctx.Cookie("username")
	ctx.SetCookie("username", cookie, -1, "/ttsx", global.App.Config.App.APPUrl, false, true)
	global.App.Log.Sugar().Infof("%s: 用户已登出", cookie)
	ctx.Redirect(http.StatusFound, "/ttsx/index")
}
